import React from 'react'
import {observable, action, computed, toJS, runInAction} from 'mobx';
import {Tools, Toast} from 'weaver-mobile';
import {BrowserHrm, RouteLayout, Browser, ListAdvanced, Form} from 'weaver-mobile-page';
import * as commonUtil from "../../util/CommonUtil";
import * as API from '../../apis/updateOperator/indexApi';
const getLabel = Tools.getLabel;

export default class UpdateOperatorStore {
    /**
     * 需要提交的参数
     * @type  
     */
    @observable workparams = {};

    /**
     * 高级搜索
     * @type {RouteLayout.Store}
     */
    @observable updateOperatorLayout = null;
    //添加流转路由
    @observable flowAddLayout = null;
    //添加流转中的操作人员路由
    @observable browserOperator = null;

    @observable uoList = new ListAdvanced.Store();

    /**
     * 核心参数从后台获取
     * @type {{isManager: boolean, showSignInput: boolean, signInputRequired: boolean, showMyTodo: boolean, showDone: boolean, showTodo: boolean, title: string}}
     */
    @observable coreparams = {
        datas: [],
        requestid: "",//流程id
        workflowid: "",
        nodeid: "",//当前节点
        nodeOptions: [],
    }

    /**
     * 临时存储选择的节点以及人员
     * @type {{}}
     */
    @observable selected = {};

    /**
     * 高级搜索表单
     * @type {Form.Store}
     */
    @observable form = new Form.Store();
    //记录来源路由
    routepath = "/upOpera";
    //数据调整次数
	changenumber = 0;


    /**
     * 页面加载初始化
     * @param contentparams
     * @param prepath
     */
    @action init = (contentparams={}, prepath = "/upOpera") => {
        let params = {requestid: 10784782, workflowid: 55022, nodeid: 46527, dialogType: 1, ...contentparams}
        runInAction(() => {
            this.routepath = prepath;
			this.workparams = contentparams;
            this.uoList = new ListAdvanced.Store({route: this.routepath, id: "upOpera"});
            this.updateOperatorLayout = new RouteLayout.Store({ route: this.routepath ,id:"search" });
            this.flowAddLayout = new RouteLayout.Store({ route: this.routepath ,id:"flowAdd" });
        })
        //初始请求
        API.loadData(params).then(res => {
            const {api_status = false, status = false} = res;
            if (api_status || status) {
                const {
                    nodeOptions = [], requestid, workflowid, nodeid, dialogType,
                    conditions = []
                } = res;
                runInAction(() => {
                    const {nodeId} = this.selected;
                    if (!nodeId && nodeOptions.length > 0) {
                        const {key, showname} = nodeOptions[0];
                        this.changeSelectNode(key, showname);
                    }
                    this.form = new Form.Store({route: this.updateOperatorLayout.path});
                    this.form.initForm(conditions,  this.updateOperatorLayout.path);
                    this.coreparams = {nodeOptions, requestid, workflowid, nodeid, dialogType};
                })
            } else {
            }
        })
        this.loaddatas();
    }

    /**
     * 流转页面初始化
     * @param prepath
     */
    @action initFlowAdd = (prepath) => {
        this.browserOperator = new BrowserHrm.Store({ route:prepath,id:"browser" });
        this.changeSelectHrm();
    }


    /**
     * 加载数据
     */
    loaddatas = () => {
        let params = {...this.workparams, ...this.form.formParams};
        this.uoList && this.uoList.clear()
        this.uoList && this.uoList.getData({
            url: API.loadDataUrl,
            method: 'POST',
            params: params
        });
    }

    //减签
    reducedSignature = (data = {}, otherparams={}) => {
        if (!(data && data.sltids)) {
            Toast.fail("请选择减签数据！");
            return;
        }
        const {showcontent=getLabel(520042, "确定要减签吗?")} = otherparams;
        commonUtil.showConfirm({
            content: showcontent,
            okEvent: () => {
                let params = {...this.workparams, ...data};
                API.doDelete(params).then(res => {
                    const {api_status = false, status = false, api_message} = res;
                    if (api_status || status) {
                        this.loaddatas();
						this.changenumber++;
                        Toast.success(api_message || getLabel(83551, "保存成功！"), 2);
                    } else {
                        Toast.fail(api_message|| getLabel(84544, "保存失败!"), 2);
                    }
                })
            }
        })
    }


    /**
     * 保存
     * @param calback
     */
    doSave = (calback) => {
        const {nodeId = "", nodeName = "", userIds = "", userNames = "", userList = []} = this.selected;
        let param = {nodeId, nodeName, userIds, userNames, userList}
        let datas = []
        datas.push(param);

        let params = {
            ...this.workparams,
            nextDirections: JSON.stringify(datas),
        };
        API.flowAddNext(params).then(res => {
            const {api_status = false, success = 0, api_message, archived = false} = res;
            if (api_status || success == 1) {
				if(archived) {//流程已归档需要强制刷新表单
					this.loading = true;
					Toast.success(getLabel(522302, "加签成功，流程已归档！"), 2, ()=>{
						window.WfForm && window.WfForm.reloadPage();
					});
					return;
				} else {
					Toast.success(api_message|| getLabel(83880, "添加成功！"), 2, calback);
				}
				this.changenumber++;
                this.loaddatas();
            } else {
                Toast.fail(api_message|| getLabel(	31877, "添加失败!"), 2, calback);
            }
        });
    }

    /**
     * 保存
     * @param calback
     */
    goSave = (calback) => {
        //校验
        let _this = this;
        const {userList = [], nodeId,userNames} = this.selected;
        if (!nodeId) {
            Toast.fail(getLabel(511479, "流转环节"), 1);
            return;
        }
        if (userList.length <= 0) {
            Toast.fail(getLabel(385003, "请选择人员"), 1);
            return;
        }
        let allNames = userNames.split(",") || [];

        let nameStr = "";
        if (allNames.length > 20) {
            nameStr = allNames.slice(0, 20).join(",") + "...";
        } else {
            nameStr = allNames.join(",");
        }

        const cssText = "margin:0 5px; font-weight: bold;color: #2db7f5";
        nameStr = `<span style='${cssText}' title='${ allNames.join(",")}'>${nameStr}</span>`;

        let confirmMsg = getLabel(513015, "确认将文件发送给$username处理？").replace("$username", nameStr);
        commonUtil.showConfirm({
            content:<span dangerouslySetInnerHTML={{__html: confirmMsg}}/>,
            okEvent: () => {
                _this.doSave( calback)
            },
        })
    }

    /**
     * 选择下一个节点
     * @param key
     * @param value
     */
    changeSelectNode = (key, value) => {
        //第一步清空数据
        let slted = {nodeId: key, nodeName: value};
        //第二步:为浏览按钮准备sqlwhere参数
        this.selected = {...this.selected, ...slted}
    }

    /**
     * 人力资源改变
     * @param ids
     * @param names
     * @param datas
     */
    changeSelectHrm = (ids, names, datas) => {
        let hrm = {userIds: ids, userNames: names, userList: datas};
        this.selected = {...this.selected, ...hrm}
    }

    /**
     * 改变核心参数
     * @param params
     */
    changeCoreParams = (params) => {
        this.coreparams = {...this.coreparams, ...params};
    }

    resetForm =() => {
        this.form.resetFields();
    }

    /**
     * 关闭销毁方法
     */
    destory = () => {
        this.workparams = {};
        this.selected = {};
        this.coreparams = {};
		this.form.resetFields();
		this.changenumber = 0;
    }
}